<template>
  <div class="login-container">
    <el-card class="box-card">
      <div class="title"></div>
      <!-- 表单 -->
      <el-form ref="form" :model="user" :rules="rules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="user.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="user.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock" show-password></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-button type="primary" @click="login">登录</el-button>
      </el-form>
      <el-link :underline="false" @click="$router.push('/reg')">还没有账号，去注册</el-link>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLogin',
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
    // 当点击登录的时候，先进行完整的验证，验证不通过就return，验证通过则提交数据
    // 表单.validator(valid => { valid===true |  valid===false })
      this.$refs.form.validate(async valid => {
        if (!valid) return // 验证不通过，return
        // console.log('验证通过，要提交的数据是：', this.user)
        const { data: res } = await loginAPI(this.user)
        if (res.code === 0) {
        // 成功：提示、存token、跳转到首页
          this.$message.success(res.message)
          // ????? 存储token。调用mutations中的updateToken，将token存储到vuex中
          this.$store.commit('user/updateToken', res.token)
        // 跳转 ？？？？
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .login-container {
    background: url(@/assets/images/login_bg.jpg) no-repeat;
    background-size: cover;
    height: 100%;
    // 标签名就是类名
    .el-card {
      width: 400px;
      // height: 310px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      .title {
        height: 40px;
        background: url(@/assets/images/login_title.png)  top center no-repeat;
      }
      .el-button {
        width: 100%;
      }

    }
  }
</style>
